package com.dragon.www.haier.util;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class CameraUtil {

    private static final String TAG = "CameraUtil";

    public static File picFile;
    public static Uri cameraUri;
    private static final String FILE_NAME_FORMAT = "yyyyMMddhhmmss";
    public static final int BITMAP_SIZE = 1200;//616;

    public final static Uri createNewFile() {
        picFile = createFile();
        return Uri.fromFile(picFile);
    }

    public static File createFile() {
        SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                FILE_NAME_FORMAT);
        Date date = new Date();
        String filename = timeStampFormat.format(date) + ".jpg";
        String filepath = Utils.getFoder("Cache/Imgcache").getAbsolutePath() + "/" + filename;
        return new File(filepath);
    }

    /**
     * 打开系统相机
     */
    public static boolean startImageCaptureIntent(Activity act, int requestid) {
        cameraUri = createNewFile();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
        Intent chooser = Intent.createChooser(intent, "选择照片");
        act.startActivityForResult(chooser, requestid);
        return true;
    }

    /**
     * 打开系统相册
     */
    public static boolean gotoAlbumView(Activity act, int requestid) {
        Uri uri = null;
        if (Utils.sdacrdExist()) {
            uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else {
            uri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
        }

        boolean flag = false;
        if (uri != null) {
            try {
                Intent intentImage = new Intent(Intent.ACTION_GET_CONTENT, uri);
                intentImage.addCategory(Intent.CATEGORY_OPENABLE);
                intentImage.setType("image/*");
                Intent chooser = Intent.createChooser(intentImage, "选择照片");
                if (chooser != null) {
                    if (requestid > 0)
                        act.startActivityForResult(chooser, requestid);
                    else
                        act.startActivity(chooser);
                    return true;
                } else {
                    flag = true;
                }
            } catch (RuntimeException e) {
                flag = true;
            }
        }
        if (flag) {
            Toast.makeText(act, "未找到相册", Toast.LENGTH_LONG).show();
        }
        return false;
    }

    public static Bitmap getBitmapFromUri(Context thisContext, Uri imgUri) {
        if (imgUri == null)
            return null;
        Uri stringUri = Uri.parse(imgUri.toString());
        String fileName = getImagePathFromURI(thisContext, stringUri);

        return getBitmap(fileName, BITMAP_SIZE);
//		return compressImage(fileName);
//		try{
//			return BitmapFactory.decodeFile(fileName);
//		}catch(Exception e){
//			EDULog.Logd(TAG, e.getMessage());
//		}
//		return null;
    }

    private static Bitmap compressImage(String filename) {
        if (filename != null) {
            Bitmap image = BitmapFactory.decodeFile(filename);
            if (image == null) {
                return null;
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
            int options = 100;
            while (baos.toByteArray().length / 1024 > 1024) { // 循环判断如果压缩后图片是否大于1M,大于继续压缩
                baos.reset();// 重置baos即清空baos
                image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
                options -= 10;// 每次都减少10
            }
            ByteArrayInputStream isBm = new ByteArrayInputStream(
                    baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
            Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
            return bitmap;
        } else {
            return null;
        }
    }

    /**
     * Convert the image URI to the file system path of the image file
     *
     * @param thisContext
     * @param imgUri
     * @return
     */
    public final static String getImagePathFromURI(Context thisContext,
                                                   Uri imgUri) {
        if (imgUri == null)
            return null;
        if ("file".equals(imgUri.getScheme())) {
            return imgUri.getPath();
        }
        // can post image
        String fileName = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = thisContext.getContentResolver().query(imgUri, proj,
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)
        if (cursor != null) {
            try {
                cursor.moveToFirst();
                int column_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                if (column_index < cursor.getCount())
                    fileName = cursor.getString(column_index);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                try {
                    if (cursor != null)
                        cursor.close();
                } catch (Exception e) {
                }
            }
        }

        return fileName;
    }

    public static String getPath(Activity activity, Uri uri) {
        String filePath = "";
        if (uri.getScheme().toString().compareTo("content") == 0) {
            Cursor cursor = activity.getContentResolver().query(uri,
                    new String[]{MediaStore.Audio.Media.DATA}, null, null, null);
            if (cursor.moveToFirst()) {
                filePath = cursor.getString(0);
            }
        } else if (uri.getScheme().toString().compareTo("file") == 0) {
            //file:///开头的uri
            filePath = uri.toString().replace("file://", "");
            //替换file://
            if (!filePath.startsWith("/mnt")) {
                //加上"/mnt"头
                filePath += "/mnt";
            }
        }
        return filePath;
    }

    private static Bitmap getBitmap(String fileName, int size) {
        if (fileName != null) {

            BitmapFactory.Options opt = new BitmapFactory.Options();
            opt.inJustDecodeBounds = true;

            try {
                BitmapFactory.decodeFile(fileName, opt);
            } catch (Exception e) {
                Log.i(TAG, e.toString());
                return null;
            }

            int width = opt.outWidth;
            int height = opt.outHeight;
            int sampleFactor = 1;

            if (width >= height)
                sampleFactor = (width / size);
            else
                sampleFactor = (height / size);

            if (sampleFactor < 1)
                sampleFactor = 1;

            opt.inSampleSize = sampleFactor;
            opt.inJustDecodeBounds = false;
            opt.inPreferredConfig = Config.ARGB_8888;
            opt.inDither = false;
            opt.inScaled = false;

            Bitmap imgBitmap = null;
            try {
                imgBitmap = BitmapFactory.decodeFile(fileName, opt);
            } catch (Exception e) {
                Log.i(TAG, e.toString());
                if (imgBitmap != null)
                    imgBitmap.recycle();
                return null;
            } catch (OutOfMemoryError oome) {
                if (imgBitmap != null && !imgBitmap.isRecycled())
                    imgBitmap.recycle();
                imgBitmap = null;
                opt.inSampleSize = sampleFactor + 1;
                try {
                    imgBitmap = BitmapFactory.decodeFile(fileName, opt);
                } catch (OutOfMemoryError oome1) {
                    if (imgBitmap != null && !imgBitmap.isRecycled())
                        imgBitmap.recycle();
                    imgBitmap = null;
                }
            }

            if (imgBitmap == null)
                return null;

            int h = imgBitmap.getHeight();
            int w = imgBitmap.getWidth();
            float ratio = 1;

            if ((h <= size) && (w <= size)) {
            } else {
                if (w >= h) {
                    ratio = (float) size / (float) w;
                } else {
                    ratio = (float) size / (float) h;
                }
            }
            // if(matrix == null) {
            // matrix = new Matrix();
            // }
            Matrix matrix = getExifInterfaceMatrix(fileName, ratio);

            // 处理旋转角度
            int angle = readPictureDegree(fileName);
            matrix.postRotate(angle);

            // matrix.setScale(ratio, ratio);
            Bitmap bitmap = null;
            try {
                bitmap = Bitmap.createBitmap(imgBitmap, 0, 0,
                        imgBitmap.getWidth(), imgBitmap.getHeight(), matrix,
                        true);
            } catch (OutOfMemoryError o) {
                o.printStackTrace();
            }
            if (!imgBitmap.equals(bitmap)) {
                imgBitmap.recycle();
            }
            imgBitmap = null;
            return bitmap;
        } else
            Log.i(TAG, "getBitmapFromUri fileName is null...");
        return null;
    }

    public static Matrix getExifInterfaceMatrix(String filename, float scale) {
        Matrix matrix = new Matrix();
        int orientation = getExifOrientation(filename);
        switch (orientation) {
            case ExifInterface.ORIENTATION_UNDEFINED:
            case ExifInterface.ORIENTATION_NORMAL:
                break;
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:// left right reversed
                // mirror
                matrix.setScale(-scale, scale);
                return matrix;
            case ExifInterface.ORIENTATION_ROTATE_180:
                matrix.setRotate(180);
                break;
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:// upside down mirror
                matrix.setScale(scale, -scale);
                return matrix;
            case ExifInterface.ORIENTATION_TRANSPOSE:// flipped about top-left <-->
                // bottom-right axis

                break;
            case ExifInterface.ORIENTATION_ROTATE_90:// rotate 90 cw to right it
                matrix.setRotate(90);
                break;
            case ExifInterface.ORIENTATION_TRANSVERSE:// flipped about top-right
                // <--> bottom-left axis

                break;
            case ExifInterface.ORIENTATION_ROTATE_270:// rotate 270 to right it
                matrix.setRotate(270);
                break;
            default:
                break;
        }
        matrix.setScale(scale, scale);
        return matrix;
    }

    public static int getExifOrientation(String filename) {
        try {
            ExifInterface exif = new ExifInterface(filename);
            // Logger.info(ExifInterface.TAG_DATETIME,
            // ""+exif.getAttribute(ExifInterface.TAG_DATETIME));
            // Logger.info(ExifInterface.TAG_GPS_LATITUDE,
            // ""+exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE));
            // Logger.info(ExifInterface.TAG_GPS_LATITUDE_REF,
            // ""+exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF));
            // Logger.info(ExifInterface.TAG_GPS_LONGITUDE,
            // ""+exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE));
            // Logger.info(ExifInterface.TAG_GPS_LONGITUDE_REF,
            // ""+exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF));
            return exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return -1;
    }

    public static File getFileFromUri(Context content, Uri uri) {
        // 获得压缩过的图片
        // 将压缩文件写到一个文件当中
        File file = createFile();
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(getImgByteArray(content, uri));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return file;
    }

    public static byte[] getImgByteArray(Context context, Uri imgUri) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        byte[] imgByte = null;
        Bitmap bitmap = null;
        try {

            bitmap = getBitmapFromUri(context, imgUri);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        if (bitmap != null) {
            try {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//				bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bytes);
                imgByte = bytes.toByteArray();
                bytes.close();
                bitmap.recycle();
            } catch (Exception e) {
                if (bitmap != null)
                    bitmap.recycle();
                imgByte = null;
                return imgByte;
            }
            bitmap = null;
        }

        return imgByte;
    }

    /**
     * 实现图片的裁剪，主要用于群组图片和用户图片的裁剪
     *
     * @param activity 调用此方法的当前activity
     * @param uri      包含有图片数据的uri
     */
    public static void startCropImage(Activity activity, Uri uri,
                                      int requestCode) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", true);
        cameraUri = createNewFile();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void startCropImage(Activity activity, Uri uri,
                                      int requestCode, int reqWidth, int reqHeight) {
        if (uri == null) {
            return;
        }
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 18);
        intent.putExtra("aspectY", 10);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", reqWidth);
        intent.putExtra("outputY", reqHeight);
        intent.putExtra("scale", true);
        cameraUri = createNewFile();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /*
     * 旋转图片
     *
     * @param angle
     *
     * @param bitmap
     *
     * @return Bitmap
     */
    public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
        // 旋转图片 动作
        Matrix matrix = new Matrix();
        ;
        matrix.postRotate(angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        return resizedBitmap;
    }
}